package com.infore.airsupervise.adapter;

import android.support.annotation.IdRes;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.DispatchAqiChartE;
import com.infore.airsupervise.bean.DispatchAqiE;
import com.infore.airsupervise.bean.DispatchAqiExpandE;
import com.infore.airsupervise.bean.DispatchSynthesisChartE;
import com.infore.airsupervise.bean.DispatchSynthesisE;
import com.infore.airsupervise.bean.DispatchSynthesisExpandE;
import com.infore.airsupervise.utils.AirLevelUtil;

import java.util.List;

import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * 实时调度-综合指数-扩展列表适配器
 * <p>
 * 作者: dingxinlin
 * 创建日期: 2017/8/18 17:51
 */

public class DispatchSynthesisExpendAdapter
        extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {

    public static final int TYPE_LEVEL_0 = 0;
    public static final int TYPE_LEVEL_1 = 1;

    public int dataType = 0; // 外部设置的数据类型

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public DispatchSynthesisExpendAdapter(List<MultiItemEntity> data) {
        super(data);
        addItemType(TYPE_LEVEL_0, R.layout.item_dispatch_synthesis);
        addItemType(TYPE_LEVEL_1,R.layout.item_dispatch_synthesis_expend);
    }

    @Override
    protected void convert(final BaseViewHolder helper, MultiItemEntity item) {

        switch (helper.getItemViewType()) {
            case TYPE_LEVEL_0:
                convertFactorItem(helper, item);
                break;

            case TYPE_LEVEL_1:
                convertChartItem(helper, item);
                break;
        }
    }

    /**
     * 因子item设值
     * @param helper
     * @param item
     */
    private void convertFactorItem(final BaseViewHolder helper, MultiItemEntity item) {
        final DispatchSynthesisExpandE aqiExpand = (DispatchSynthesisExpandE) item;
        DispatchSynthesisE.SynthesisBean nearData = aqiExpand.nearData;

        // 气象参数、时间
        helper.setText(R.id.station_name, aqiExpand.staName);
        helper.setText(R.id.humidity_wind, "湿:"+ (int)nearData.getHumidity() +"%  风:"+ nearData.getSpeed() +"m/s");
        helper.setText(R.id.data_time, nearData.getTime());

        // 因子参数
        helper.setText(R.id.tv_api, nearData.getAPI().getIndex() + "");
        helper.setText(R.id.tv_pm25, nearData.getPM25().getIndex() + "");
        helper.setText(R.id.tv_pm10, nearData.getPM10().getIndex() + "");
        helper.setText(R.id.tv_so2, nearData.getSO2().getIndex() + "");
        helper.setText(R.id.tv_no2, nearData.getNO2().getIndex() + "");
        helper.setText(R.id.tv_co, nearData.getCO().getIndex() + "");
        helper.setText(R.id.tv_o3, nearData.getO3().getIndex() + "");

        // 背景色
        helper.setBackgroundRes(R.id.label_api,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_AQI, nearData.getAPI().getValue()));
        helper.setBackgroundRes(R.id.label_pm25,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_PM25, nearData.getPM25().getValue()));
        helper.setBackgroundRes(R.id.label_pm10,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_PM10, nearData.getPM10().getValue()));
        helper.setBackgroundRes(R.id.label_so2,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_SO2, nearData.getSO2().getValue()));
        helper.setBackgroundRes(R.id.label_no2,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_NO2, nearData.getNO2().getValue()));
        helper.setBackgroundRes(R.id.label_co,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_CO, nearData.getCO().getValue()));
        helper.setBackgroundRes(R.id.label_o3,
                AirLevelUtil.getFactorLevelColor(StatusConst.AIR_TYPE_O3, nearData.getO3().getValue()));

        // 风向角
        ImageView windDir = helper.getView(R.id.wind_direction);
        windDir.animate().rotation(nearData.getSpeedDir());

        // item点击事件
        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int pos = helper.getAdapterPosition();
                if (aqiExpand.isExpanded()) {
                    collapse(pos);
                } else {
                    expand(pos);
                }
            }
        });
    }

    /**
     * 转换图表item
     * @param helper
     * @param item
     */
    private void convertChartItem(BaseViewHolder helper, MultiItemEntity item) {
        final DispatchSynthesisExpandE.FactorTrendE factorTrend = (DispatchSynthesisExpandE.FactorTrendE) item;

        // 实例WebView
        final WebView mWebView = new WebView(this.mContext.getApplicationContext());

        // 将WebView加入容器
        FrameLayout webContainer = helper.getView(R.id.web_container);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView.setLayoutParams(layoutParams);
        webContainer.addView(mWebView);

        // 配置WebView
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setDomStorageEnabled(false);
        settings.setAppCacheEnabled(false);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        // 不用系统浏览器打开,直接显示在当前WebView
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mWebView.loadUrl("javascript:refresh('"
                        + getChartNeedData(factorTrend.dataList) + "')");
            }
        });

        // 加载网页文件
        mWebView.loadUrl("file:///android_asset/chart-dispatch-synthesis.html");
    }

    /**
     * 转换为图标需要的数据格式
     * @param dataList
     */
    private String getChartNeedData(List<DispatchSynthesisE.SynthesisBean> dataList) {

        DispatchSynthesisChartE chartE = new DispatchSynthesisChartE();

        // 标题信息
        chartE.setTitle(getChartTitle());

//        DispatchSynthesisChartE.Series seriesApi = new DispatchSynthesisChartE.Series();
//        seriesApi.setName("综指");
        DispatchSynthesisChartE.Series seriesPm25 = new DispatchSynthesisChartE.Series();
        seriesPm25.setName("PM2.5");
        DispatchSynthesisChartE.Series seriesPm10 = new DispatchSynthesisChartE.Series();
        seriesPm10.setName("PM10");
        DispatchSynthesisChartE.Series seriesSo2 = new DispatchSynthesisChartE.Series();
        seriesSo2.setName("SO2");
        DispatchSynthesisChartE.Series seriesNo2 = new DispatchSynthesisChartE.Series();
        seriesNo2.setName("NO2");
        DispatchSynthesisChartE.Series seriesCo = new DispatchSynthesisChartE.Series();
        seriesCo.setName("CO");
        DispatchSynthesisChartE.Series seriesO3 = new DispatchSynthesisChartE.Series();
        seriesO3.setName("O3");

        // X\Y轴信息
        for (DispatchSynthesisE.SynthesisBean data : dataList) {
            // x轴的时间
            chartE.getCategories().add(data.getTime());

            // 各系列数据
//            seriesApi.getData().add(data.getAPI().getIndex());
            seriesPm25.getData().add(data.getPM25().getIndex());
            seriesPm10.getData().add(data.getPM10().getIndex());
            seriesSo2.getData().add(data.getSO2().getIndex());
            seriesNo2.getData().add(data.getNO2().getIndex());
            seriesCo.getData().add(data.getCO().getIndex());
            seriesO3.getData().add(data.getO3().getIndex());
        }

//        chartE.getSeries().add(seriesApi);
        chartE.getSeries().add(seriesPm25);
        chartE.getSeries().add(seriesPm10);
        chartE.getSeries().add(seriesSo2);
        chartE.getSeries().add(seriesNo2);
        chartE.getSeries().add(seriesCo);
        chartE.getSeries().add(seriesO3);

        return JSON.toJSONString(chartE);
    }

    /**
     * 获取图表标题
     */
    private String getChartTitle() {
        String[] timeStrs = new String[]{"近4小时", "近24小时", "近30天"};

        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0; i<timeStrs.length; i++) {
            if (i == dataType) {
                stringBuffer.append(timeStrs[i]);
                break;
            }
        }
        stringBuffer.append("污染物权重变化趋势");

        return stringBuffer.toString();
    }
}
